import { defineStore } from 'pinia'
import { ref } from 'vue'
import { 
  getUserOrders, 
  getOrderDetail, 
  createOrder, 
  cancelOrder,
  type Order 
} from '@/api/order'

export const useOrderStore = defineStore('order', () => {
  const orders = ref<Order[]>([])
  const currentOrder = ref<Order | null>(null)
  const loading = ref(false)
  const total = ref(0)
  const currentPage = ref(0)

  // 获取用户订单列表
  const fetchOrders = async (userId: number, params?: {
    page?: number
    size?: number
    status?: string
  }) => {
    try {
      loading.value = true
      const response = await getUserOrders(userId, params)
      console.log('订单列表API响应:', response)
      if (response.data && response.data.success) {
        orders.value = response.data.orders
        total.value = response.data.totalElements
        currentPage.value = response.data.currentPage
      }
      return response.data
    } catch (error: any) {
      console.error('获取订单列表失败:', error)
      return { success: false, message: error.response?.data?.message || '获取订单列表失败' }
    } finally {
      loading.value = false
    }
  }

  // 获取订单详情
  const fetchOrderDetail = async (userId: number, orderId: number) => {
    try {
      loading.value = true
      const response = await getOrderDetail(userId, orderId)
      if (response.data && response.data.success) {
        currentOrder.value = response.data.order
      }
      return response.data
    } catch (error: any) {
      console.error('获取订单详情失败:', error)
      return { success: false, message: error.response?.data?.message || '获取订单详情失败' }
    } finally {
      loading.value = false
    }
  }

  // 创建订单
  const addOrder = async (userId: number, orderData: any) => {
    try {
      loading.value = true
      const response = await createOrder(userId, orderData)
      if (response.data && response.data.success) {
        // 重新获取订单列表
        await fetchOrders(userId)
      }
      return response.data
    } catch (error: any) {
      console.error('创建订单失败:', error)
      return { success: false, message: error.response?.data?.message || '创建订单失败' }
    } finally {
      loading.value = false
    }
  }

  // 取消订单
  const cancelOrderById = async (userId: number, orderId: number) => {
    try {
      loading.value = true
      const response = await cancelOrder(userId, orderId)
      if (response.data && response.data.success) {
        // 重新获取订单列表
        await fetchOrders(userId)
      }
      return response.data
    } catch (error: any) {
      console.error('取消订单失败:', error)
      return { success: false, message: error.response?.data?.message || '取消订单失败' }
    } finally {
      loading.value = false
    }
  }

  // 清空状态
  const clearOrders = () => {
    orders.value = []
    currentOrder.value = null
    total.value = 0
    currentPage.value = 0
  }

  return {
    orders,
    currentOrder,
    loading,
    total,
    currentPage,
    fetchOrders,
    fetchOrderDetail,
    addOrder,
    cancelOrderById,
    clearOrders
  }
})